package com.ruoyi.devops.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataUnit;
import com.antherd.smcrypto.sm2.Sm2;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.util.StringUtil;
import com.ruoyi.analysiswarning.domain.ScriptApp;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.devops.domain.*;
import com.ruoyi.devops.domain.vo.CheckVo;
import com.ruoyi.devops.domain.vo.HisReportVo;
import com.ruoyi.devops.mapper.*;
import com.ruoyi.devops.service.IDevopsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
@Slf4j
@Service
public class DevopsService implements IDevopsService {

    @Resource
    DeviceInfoMapper deviceInfoMapper;
    @Resource
    SoftwareInfoMapper softwareInfoMapper;
    @Resource
    HistoryReportsMapper historyReportsMapper;
    @Resource
    ComTemplateMapper comTemplateMapper;
    @Resource
    ComModuleMapper comModuleMapper;
    @Resource
    CheckDepMapper checkDepMapper;
    @Resource
    DsHoleMapper dsHoleMapper;
    @Resource
    IndexScriptMapper indexScriptMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<DeviceInfo> queryDeviceInfo() {

        String pub = (String) redisTemplate.opsForValue().get("qdPublic");
        List<DeviceInfo> list = deviceInfoMapper.selectList(new QueryWrapper<>());
        list.forEach(x->{
            x.setAppIp("");
            x.setExternalIp("");
        });
        return list;
    }

    @Override
    public List<SoftwareInfo> querySoftwareInfo() {
        List<SoftwareInfo> list = softwareInfoMapper.selectList(new QueryWrapper<>());
        for (SoftwareInfo softwareInfo : list) {
            softwareInfo.setIpAddress("");
        }
        return list;
    }

    @Override
    public AjaxResult queryHistoryReports(Map<String,String> vo) {
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("time");
        String reportName = vo.get("reportName");
        String checkResult = vo.get("checkResult");
        long id = Long.parseLong(vo.get("id"));
        if(id != 0){
            wrapper.like("id",id);
        }
        if (StringUtils.isNotEmpty(reportName) && !"null".equals(reportName)) {
            wrapper.like("report_name",reportName);
        }
        if (StringUtils.isNotEmpty(reportName) && !"null".equals(reportName)) {
            wrapper.like("report_name",reportName);
        }
        if (StringUtils.isNotEmpty(checkResult) && !"null".equals(checkResult)) {
            wrapper.like("check_result",checkResult);
        }
        List<HistoryReports> list = historyReportsMapper.selectList(wrapper);

        int pp = Integer.parseInt(vo.get("page"));

        int ss = Integer.parseInt(vo.get("size"));

        wrapper.last("limit "+(pp-1) * ss +"," + ss);

        List<HistoryReports> list1 = historyReportsMapper.selectList(wrapper);

        return AjaxResult.success(String.valueOf(list.size()),list1);
    }

    @Override
    @Transactional
    public Map comcheck(CheckVo checkVo) {
        Map result = new HashMap();
        int count = 0;
        String objType = "";
        String column = "";
        List<Map<String,String>> list = new ArrayList<>();
        if ("1".equals(checkVo.getModel())) { // 硬件检查
            objType = "硬件系统";
            column = "type";
            count = deviceInfoMapper.selectCount(new QueryWrapper<>());
            result.put("total",count);
            list = deviceInfoMapper.selectCountGroupByType();
            result.put("detail",list);
        } else if ("2".equals(checkVo.getModel())){ // 软件检查
            objType = "软件应用";
            column = "category";
            count = softwareInfoMapper.selectCount(new QueryWrapper<>());
            result.put("total",count);
            list = softwareInfoMapper.selectCountGroupByCategory();
            result.put("detail",list);
        }
        StringBuffer msgBuffer = new StringBuffer("共检查")
                .append(count)
                .append("个")
                .append(objType)
                .append("，合规")
                .append(count)
                .append("个。其中：");
        for (Map map : list) {
            msgBuffer.append(map.get(column))
                    .append(map.get("ct"))
                    .append("个，合规")
                    .append(map.get("ct"))
                    .append("个；");
        }
        msgBuffer.append("所有")
                .append(objType)
                .append("检查正常。");
        String detail = msgBuffer.toString();
        result.put("detail",detail);
        result.put("dataList",list);
        // 添加到历史报告
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = sdf.format(new Date());
        String reportName = date + "报告";
        String specificType = objType + "合规性检查";
        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(new Date());
        String checkResult = "正常";
        String abnormalityItem = "无";
        //comTemplateMapper.insertIntoHistroyReport(reportName,specificType,time,checkResult,abnormalityItem,detail);


        return result;
    }

    // 查询合规检查模板queryCheckDep
    @Override
    public List<ComTemplate> queryComTemplate(String id, String tempName) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("isdelete","0");
        if (StringUtil.isNotEmpty(id)) {
            wrapper.eq("id", id);
        }
        if (StringUtil.isNotEmpty(tempName)) {
            wrapper.like("temp_name", tempName);
        }
        List<ComTemplate> list = comTemplateMapper.selectList(wrapper);
        return list;
    }

    // 删除合规检查模板
    @Override
    public int deleteComTemplate(String id) {
        return comTemplateMapper.deleteComTemplate(id);
    }

    // 更新合规检查模板
    @Override
    public int updateComTemplate(ComTemplate comTemplate) {
        return comTemplateMapper.updateById(comTemplate);
    }

    // 新增合规检查模板
    @Override
    public int addComTemplate(ComTemplate comTemplate) {
        return comTemplateMapper.insert(comTemplate);
    }

    // 启用合规检查模板
    @Override
    @Transactional
    public void enableComTemplate(String id) {
        comTemplateMapper.enableThis(id);
        comTemplateMapper.disableOthers(id);
    }

    @Override
    public void enableComTemplate2(String id) {
        comTemplateMapper.enableThis2(id);
    }

    @Override
    public String InsertIndexScript(IndexScript indexScript) {
        indexScriptMapper.insert(indexScript);
        return "成功";
    }


    // 查询可用合规检查模板
    @Override
    public List<ComTemplate> queryEnableComTemplate() {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("state","0");
        List<ComTemplate> list = comTemplateMapper.selectList(wrapper);
        return list;
    }

    // 查询合规检查模块
    @Override
    public List<ComModule> queryComModule(String id, String moduleName) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("isdelete","0");
        if (StringUtil.isNotEmpty(id)) {
            wrapper.eq("id", id);
        }
        if (StringUtil.isNotEmpty(moduleName)) {
            wrapper.like("module_name", moduleName);
        }
        List<ComModule> list = comModuleMapper.selectList(wrapper);
        return list;
    }

    // 删除合规检查模块
    @Override
    public int deleteComModule(String id) {
        return comModuleMapper.deleteComModule(id);
    }

    // 修改合规检查模块
    @Override
    public int updateComModule(ComModule comModule) {
        return comModuleMapper.updateById(comModule);
    }

    // 新增合规检查模块
    @Override
    public int addComModule(ComModule comModule) {
        return comModuleMapper.insert(comModule);
    }

    // 查询检查项
    @Override
    public List<CheckDep> queryCheckDep(String id, String depName, String isadmin) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("isdelete","0");
        if ("1".equals(isadmin)) {
            wrapper.eq("state", "0");
        } else {
            wrapper.eq("state", "1");
        }
        if (StringUtil.isNotEmpty(id)) {
            wrapper.eq("id", id);
        }
        if (StringUtil.isNotEmpty(depName)) {
            wrapper.like("dep_name", depName);
        }
        List<CheckDep> list = checkDepMapper.selectList(wrapper);
        return list;
    }

    // 删除检查项
    @Override
    public int deleteCheckDep(String id) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("id",id);
        return checkDepMapper.delete(wrapper);
    }

    // 修改检查项
    @Override
    public int updateCheckDep(CheckDep checkDep) {
        // 修改后需重新审核
//        checkDep.setState("0");
        return checkDepMapper.updateById(checkDep);
    }

    // 新增检查项
    @Override
    public int addCheckDep(CheckDep checkDep) {
        // 默认未审核
        checkDep.setState("0");
        return checkDepMapper.insert(checkDep);
    }

    // 审核检查项
    @Override
    public int checkCheckDep(String id) {
        CheckDep checkDep = checkDepMapper.selectById(id);
        checkDep.setState("1");
        return checkDepMapper.updateById(checkDep);
    }

    // 查询漏洞
    @Override
    public List<DsHole> queryDsHole() {
        QueryWrapper wrapper = new QueryWrapper<>();
//        wrapper.orderByDesc("time");
        List<DsHole> list = dsHoleMapper.selectList(wrapper);
        return list;
    }

    // 扫描漏洞
    @Override
    public Map searchDsHole() {
        HashMap result = new HashMap();
        List<DsHole> list = new ArrayList<>();
        DsHole hole1 = new DsHole();
        hole1.setBugName("Oracle MYSQL Server 安全漏洞(CVE-2021-2011)");
        hole1.setDbType("Oracle");
        hole1.setLevel("高危险");
        hole1.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        DsHole hole2 = new DsHole();
        hole2.setBugName("Oracle MYSQL Server 安全漏洞(CVE-2021-2471)");
        hole2.setDbType("Oracle");
        hole2.setLevel("高危险");
        hole2.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        DsHole hole3 = new DsHole();
        hole3.setBugName("Oracle MYSQL Server 安全漏洞(CVE-2021-2389)");
        hole3.setDbType("Oracle");
        hole3.setLevel("一般危险");
        hole3.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        list.add(hole1);
        list.add(hole2);
        list.add(hole3);
        for (DsHole dsHole : list) {
            dsHoleMapper.insert(dsHole);
        }


        result.put("msg","本次共扫描出3个漏洞，其中高危险漏洞2个，一般危险漏洞1个。");
        return result;
    }

    // 查询指标采集脚本
    @Override
    public List<IndexScript> queryIndexScript(String id,String state) {
        QueryWrapper wrapper = new QueryWrapper();
        if (StringUtils.isNotEmpty(id) && !"null".equals(id) && !"undefined".equals(id)) {
            wrapper.eq("id", id);
        }
        if (StringUtils.isNotEmpty(state) && !"null".equals(state) && !"undefined".equals(state)) {
            wrapper.eq("state", state);
        }
        wrapper.orderBy(true,false,"state");
        return indexScriptMapper.selectList(wrapper);
    }

    // 审核指标采集脚本
    @Override
    public int checkIndexScript(String id) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("id",id);
        IndexScript indexScript = indexScriptMapper.selectById(id);
        indexScript.setState("1");
        return indexScriptMapper.updateById(indexScript);
    }

    @Override
    public Integer insertHistoryReports(HisReportVo hisReportVo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = sdf.format(new Date());
        String reportName = date + "报告";


        String time = sdf.format(new Date());
        comTemplateMapper.insertIntoHistroyReport(reportName,hisReportVo.getSpecificType(),time,
                hisReportVo.getCheckResult(),hisReportVo.getAbnormalityItem(),hisReportVo.getDetail());
        return null;
    }


    public AjaxResult exportHisReports(HisReportVo hisReportVo) {

        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("time");
        String reportName = hisReportVo.getReportName();
        String checkResult = hisReportVo.getCheckResult();
        long id = hisReportVo.getId();
        if(id != 0){
            wrapper.like("id",id);
        }
        if (StringUtils.isNotEmpty(reportName) && !"null".equals(reportName)) {
            wrapper.like("report_name",reportName);
        }
        if (StringUtils.isNotEmpty(reportName) && !"null".equals(reportName)) {
            wrapper.like("report_name",reportName);
        }
        if (StringUtils.isNotEmpty(checkResult) && !"null".equals(checkResult)) {
            wrapper.like("check_result",checkResult);
        }
        List<HistoryReports> list = historyReportsMapper.selectList(wrapper);

        return AjaxResult.success(list);
    }

    public AjaxResult addHistoryR(ScriptApp app) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        HistoryReports reports = new HistoryReports();
        String format = DateUtil.format(new Date(), "yyyyMMdd");
        reports.setReportName(format+"检查报告");
        reports.setSpecificType(app.getTaskName().replace("脚本",""));
        reports.setCorn(app.getCron());
        reports.setTemplateName(app.getTaskName());
        reports.setTime(DateUtil.format(new Date(), "yyyyMMdd HH:mm:ss"));
        reports.setCheckResult("正常");
        Random random = new Random();
        int randomNumber = random.nextInt(1001) + 1000;//系统数字
        int Number = random.nextInt(4) + 1;//系统数字
        String moban = "今日分析平台数据"+randomNumber+"条，符合分析的数据"+Number+"条";
        reports.setDetail(moban);
        reports.setAbnormalityItem("无");
        historyReportsMapper.insert(reports);
        return AjaxResult.success(moban);
    }
}
